package com.hmdp.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.SHOP_TYPE_LIST;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ShopTypeMapper shopTypeMapper;
    /**
     * 查询店铺类型列表
     * @return
     */
    @Override
    public Object queryTypeList() {
        //1.从redis中查询店铺类型列表
        List<String> typeList = stringRedisTemplate.opsForList().range(SHOP_TYPE_LIST, 0, -1);
        List<ShopType> shopTypes = new ArrayList<>();
        //2.判断是否存在
        if (!typeList.isEmpty()) {
            //3.存在，直接返回
            for (String string : typeList) {
                ShopType shopType = JSONUtil.toBean(string, ShopType.class);
                shopTypes.add(shopType);
            }
            return shopTypes;
        }
        //4.不存在，查询数据库
        LambdaQueryWrapper<ShopType> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(ShopType::getSort);
        shopTypes= shopTypeMapper.selectList(lambdaQueryWrapper);
        //5.判断是否为空
        if(shopTypes.isEmpty()){
            //6.不存在，报错404
            return Result.fail("店铺类型列表不存在");
        }
        //7.存在，存入redis并返回数据
        for(ShopType shopType : shopTypes){
            String jsonStr = JSONUtil.toJsonStr(shopType);
            typeList.add(jsonStr);
        }
        stringRedisTemplate.opsForList().rightPushAll(SHOP_TYPE_LIST,typeList);
        return shopTypes;
    }
}
